import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Balloon, Button } from '@teamix/ui';
import Pagination from 'components/commonPagination';
import { YunxiaoTable, Title } from '@alife/devops-ui';
import utils from 'utils';
import exceed from 'utils/apimap';
import track from 'utils/track';
import ReportSwitch from './switch';
import GuaranteeModal from './guaranteeModal';
import './index.scss';
import intl from '../../../../../../../../../../locale';

const { organization_id: org_id } = window.FORCE.organization;

export default class DisableReposDialog extends React.Component {
  static propTypes = {
    trigger: PropTypes.element,
  };

  static defaultProps = {
    trigger: null,
  };

  constructor(props) {
    super(props);

    this.state = {
      isModalOpen: false,
      isLoading: true,
      page: 1,
      selectedRowKeys: [],
      isGuaranteeModalOpen: false,
    };
  }

  // 敏感信息报表-查询代码库分页列表
  getInfoReportDisableRepos(page) {
    this.setState({
      isLoading: true,
    });

    exceed
      .forceFetch({
        api: 'organization.sensitive.info_report.overview_projects',
        params: {
          org_id,
        },

        data: {
          per_page: 10,
          page,
          order_by: 'project_created_at',
          sort: 'desc',
          integration_service: 'sensitive_info_detection',
          is_open: false,
        },
      })
      .then((result) => {
        const { list } = result;
        const total = result.amount || 0;
        this.setState({
          infoReportDisableRepos: list,
          isLoading: false,
          total,
          page,
        });
      });
  }

  showModal = () => {
    this.getInfoReportDisableRepos(1);

    this.setState({
      isModalOpen: true,
    });

    track({
      action: 'view_repo_list',
      page: 'Organization-Settings-Risk Control',
      type: 'Sensitive Info Report',
    });
  };

  onClose = () => {
    this.setState({
      isModalOpen: false,
      isGuaranteeModalOpen: false,
    });
  };

  onPageNoChange = (page) => {
    this.getInfoReportDisableRepos(page);
  };

  handleBatcnOpen = () => {
    const { selectedRowKeys } = this.state;
    this.props.batchOpenService(selectedRowKeys, () => {
      this.onClose();
      window.location.reload();
    });
  };

  render() {
    const {
      infoReportDisableRepos,
      isLoading,
      total,
      page,
      selectedRowKeys,
      isGuaranteeModalOpen,
    } = this.state;
    const { isBatchOpening } = this.props;
    return (
      <React.Fragment>
        {this.state.isModalOpen ? (
          <Dialog
            title={intl.get({
              id: 'code-assets.containers.sensitiveInfoReport.disableReposDialog.LibrariesWithScanDisabled',
              defaultMessage: '未开启扫描的库',
            })}
            visible
            onCancel={this.onClose}
            onClose={this.onClose}
            footer={false}
          >
            <div style={{ width: '798px' }}>
              <ReportSwitch
                inDialog
                dialogCallback={() => {
                  this.onClose();
                  window.location.reload();
                }}
                {...this.props}
              />

              <YunxiaoTable
                className={`disable-repos-table ${selectedRowKeys.length ? 'selected' : ''}`}
                hasBorder
                dataSource={infoReportDisableRepos}
                loading={isLoading}
                primaryKey="project_id"
                rowSelection={{
                  selectedRowKeys,
                  onChange: (keys) => {
                    this.setState({
                      selectedRowKeys: keys,
                    });
                  },
                  getProps: () => {
                    return {
                      disabled: false,
                    };
                  },
                  columnProps: () => {
                    return {
                      lock: 'none', // 组件内规则，只要有锁列，那么默认选择列左锁列
                    };
                  },
                  titleAddons: () => {
                    if (!selectedRowKeys.length) {
                      return null;
                    }
                    return (
                      <span className="op-container" key="op-container">
                        <span
                          className="total-tip"
                          style={{ position: 'relative', top: '2px', marginLeft: '3px' }}
                        >
                          {intl.get(
                            {
                              id: 'code-assets.containers.sensitiveInfoReport.disableReposDialog.SelectedrowkeyslengthIsSelected',
                              defaultMessage: '已选择 {selectedRowKeysLength} 项',
                            },
                            { selectedRowKeysLength: selectedRowKeys.length },
                          )}
                        </span>
                        <Button
                          size="small"
                          type="primary"
                          text
                          onClick={() => {
                            this.setState({
                              isGuaranteeModalOpen: true,
                            });
                          }}
                          style={{ marginLeft: 12, lineHeight: 17 }}
                        >
                          {intl.get({
                            id: 'code-assets.containers.sensitiveInfoReport.disableReposDialog.Open',
                            defaultMessage: '开启',
                          })}
                        </Button>
                      </span>
                    );
                  },
                }}
              >
                <YunxiaoTable.Column
                  title={intl.get({
                    id: 'code-assets.containers.sensitiveInfoReport.disableReposDialog.CodeBase',
                    defaultMessage: '代码库',
                  })}
                  dataIndex="project_name"
                  cell={(value, index, record) => {
                    return (
                      <Title
                        trigger={
                          <a
                            href={`/${record.organization_id}/${record.project_path}`}
                            target="_blank"
                            rel="noreferrer"
                          >
                            {record.project_name}
                          </a>
                        }
                      >
                        <div>{record.project_name}</div>
                      </Title>
                    );
                  }}
                  className={'repo-col'}
                  width={300}
                />

                <YunxiaoTable.Column
                  title={intl.get({
                    id: 'code-assets.containers.sensitiveInfoReport.disableReposDialog.DatabaseAdministrator',
                    defaultMessage: '库管理员',
                  })}
                  dataIndex="project_name"
                  cell={(value, index, record) => {
                    const admins =
                      record.admin_users && record.admin_users.length
                        ? record.admin_users.map((item) => item.name).join('，')
                        : '-';
                    const adminTrigger = <div className="table-cell-one-line">{admins}</div>;
                    return (
                      <Balloon.Tooltip trigger={adminTrigger} align="t">
                        {admins}
                      </Balloon.Tooltip>
                    );
                  }}
                  className="project-name-col"
                  width={200}
                />

                <YunxiaoTable.Column
                  title={intl.get({
                    id: 'code-assets.containers.sensitiveInfoReport.disableReposDialog.Openness',
                    defaultMessage: '公开性',
                  })}
                  dataIndex="visibility_level"
                  cell={(value, index, record) => {
                    return utils.getVisibilityLevelsText(record.visibility_level);
                  }}
                  width={140}
                />
              </YunxiaoTable>
              <Pagination
                onChange={this.onPageNoChange}
                current={page}
                total={total}
                showJump={false}
                footerProps={{
                  style: { border: 'none' },
                }}
              />
            </div>
          </Dialog>
        ) : null}
        {!!this.props.trigger &&
          React.cloneElement(this.props.trigger, { onClick: this.showModal })}
        {isGuaranteeModalOpen && (
          <GuaranteeModal
            isModalOpen={isGuaranteeModalOpen}
            okFn={() => {
              this.handleBatcnOpen();
            }}
            isOpeningService={isBatchOpening}
            closeFn={() => {
              this.setState({
                isGuaranteeModalOpen: false,
              });
            }}
          />
        )}
      </React.Fragment>
    );
  }
}
